<?php

include_once 'application/functions.php';


/**
 * Controller class.
 */
class Web_Controller extends Psa_Plugin_Controller{


	/*
	 * Reference to result object
	 */
	protected $psa_result;
	
	
	/*
	 * Controller main method
	 */
	function psa_main($url_args){

		// global config arrays
		global $PSA_CFG, $CFG;
		
		// make action function name from url
		$action_method = trim($url_args[0]);
		
		// put reference to this controller object into registry
		Psa_Registry::get_instance()->Web_Controller = $this;
		
		// reference to result object
		$this->psa_result = Psa_Result::get_instance();
		
		// put some default values in result object that you will need on every request
		// regardless of is user authorized or not
		if(@$_SERVER["HTTP_X_REQUESTED_WITH"] == 'XMLHttpRequest')
			$this->psa_result->ajax_request = 1;
		else
			$this->psa_result->ajax_request = 0;
		$this->psa_result->basedir_web = $PSA_CFG['folders']['basedir_web'];
		$this->psa_result->html_page_title = $CFG['app_name'];
		$this->psa_result->app_version = $CFG['app_ver'];
		
		// include all action methods
		include_once 'application/controllers/Web_Controller_Actions.php';

		// make new object with action methods
		$web_actions = new Web_Controller_Actions($this);
		
		// check if we have defined requested action, if not call index action by default
		if(!method_exists($web_actions, $action_method))
			$action_method = 'index';

		// call action and if Unauthorized_Access_Exception raised call login action 
		try{
			$web_actions->$action_method($url_args);
		}
		catch (Unauthorized_Access_Exception $e){
			$web_actions->login($url_args);
		}
		catch (Aaieduhr_Single_Logout_Exception $e){
			$web_actions->logout('Aaieduhr_Single_Logout');
		}
	}

	
	/**
	 * Runs plugins.
	 * @param array $run_plugins argument for psa_run_plugins() function.
	 */
	function run_plugins($run_plugins){
		
		// first run model plugins and catch all exceptions
		try {
			if(isset($run_plugins['model']))
				psa_run_plugins($run_plugins['model']);
		}
		// if any exception is raised call error page
		catch (Exception $e){
			$run_plugins = array();
			$run_plugins['view']['Main_View']['uncaught_exception_redirect'] = array($e);
		}
		
		// After model plugins are called, assign all results from models (every property in $this->psa_result object)
		// to smarty ($psa_smarty) object. I use smarty template engine here.
		$this->smarty_assign_object_properties($this->psa_result);
		
		// run view plugins at the end
		if(isset($run_plugins['view']))
			psa_run_plugins($run_plugins['view']);
	}
	
	
	/**
	 * Checks login and sets some values to registry object and session.
	 * @param string $session_id
	 */
	function check_login(){
		
		global $CFG;
		
		// new user object
		$user = new Psa_User();
		
		
		// Check if we have user object stored in session.
		// That means that user is already authorized.
		if(!$user->session_restore()){
			
			// check if login data are sent from login form
			if(in_array('local_user', $CFG['login_method']) && (isset($_POST['login_user']) && isset($_POST['login_pass']))){
				$user->username = $_POST['login_user'];
				$user->password = $_POST['login_pass'];
				if(!$user->authorize()){
					$this->psa_result->unsuccessful_authorize = 1;
				}
			}
			// AAI@EduHr SSO login
			else if(in_array('aaieduhr_sso', $CFG['login_method']) && isset($_GET['aaieduhr_sso_login'])){
				
				require_once($CFG['simplesamlphp']['include']);
				$as = new SimpleSAML_Auth_Simple($CFG['simplesamlphp']['authentication_source']);
				
				if(!$as->isAuthenticated()){
					$as->requireAuth(array('ReturnTo' => $CFG['simplesamlphp']['after_sso_login_url']));
				}
				
				$sso_attributes = $as->getAttributes();
				
				if(isset($sso_attributes['hrEduPersonUniqueID'][0])){
					
					// if SSO user is allowed
					if(is_allowed_sso_user($sso_attributes['hrEduPersonUniqueID'][0])){
	
						// check if user already exists
						$user->username = $sso_attributes['hrEduPersonUniqueID'][0];
						
						// create new user
						if(!$user->authorize('username') && @$CFG['sso']['default_user_group']){
							$user = new Psa_User('new');
							$user->aaieduhr_sso = 1; // flag that user is logged in from sso
							$user->username = $sso_attributes['hrEduPersonUniqueID'][0];
							$user->password = md5(microtime()); // anything because password is useless for SSO users
							
							try{
								$user->first_name = $sso_attributes['givenName'][0];
								$user->last_name = $sso_attributes['sn'][0];
								$user->email = $sso_attributes['mail'][0];
								
								$user->save();
								$user->add_group($CFG['sso']['default_user_group']);					
							}
							catch(Psa_User_Exception $e){
								$this->psa_result->unsuccessful_authorize = 1;
							}
						}
					}
					else{
						$this->psa_result->unpermitted_sso_user = $sso_attributes['hrEduPersonUniqueID'][0];
						$this->psa_result->aaieduhr_sso_logout_url = $CFG['sso']['logout_url'];
					}
				}
			}
			
			// This will happen only once when user is logged in.
			// Put here things that you want to store in session or do
			// only when user is authorized.
			if($user->authorized){
				
				// set user groups
				//$user->set_groups();
				
				// save last login time
				$user->save_last_login_time();
				
				// serialize user object into session
				$user->session_save();
				
				// flag to not to check single logout
				$do_not_check_aaieduhr_logout = 1;
			}
		}
		
		
		if(@$user->aaieduhr_sso){
			
			if(!isset($do_not_check_aaieduhr_logout)){
				// check if we have AAI@EduHr single logout
				require_once($CFG['simplesamlphp']['include']);
				$as = new SimpleSAML_Auth_Simple($CFG['simplesamlphp']['authentication_source']);
				
				// check if SSO session is valid
				if(!$as->isAuthenticated()){
					// throw Aaieduhr_Single_Logout_Exception
					include_once 'plugins/Aaieduhr_Single_Logout_Exception.php';
					throw new Aaieduhr_Single_Logout_Exception("AAI@EduHr single logout", false);
				}
			}
			
			$_SESSION['aaieduhr_sso_user'] = $this->psa_result->aaieduhr_sso_user = 1;
		}
		
		
		// This will happen on every request after user is authorized.
		if($user->authorized){
			
			// put reference to user object into registry
			Psa_Registry::get_instance()->user = $user;
			
			// some values that will be available in all templates
			$this->psa_result->username = $user->username;
		}
		// user is not authorized
		else{
			// throw Unauthorized_Access_Exception
			include_once 'application/exceptions/Unauthorized_Access_Exception.php';
			throw new Unauthorized_Access_Exception("Login needed", false);
		}
	}
}
